package com.d4a5.mapping.google2
{
	import com.d4a5.mapping.core.AmfFactory;
	import com.d4a5.mapping.core.AmfObject;
	import com.d4a5.mapping.core.AmfPackage;
	import com.d4a5.mapping.core.AmfPackages;
	
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;

	public class wmgOverlayLayerAmfPuller extends wmgOverlayLayer
	{
		protected var _url:String;
		protected var _urlChanged:Boolean = false;
		protected var _puller:URLLoader;
		
		public function wmgOverlayLayerAmfPuller()
		{
			super();
			
			this._puller = new URLLoader();
			this._puller.addEventListener(Event.COMPLETE,onAmfPullComplete);
			this._puller.dataFormat = URLLoaderDataFormat.BINARY;
		}
		
		public function get url() : String {
			return this._url;
		}
		
		public function set url( u:String ) : void {
			if( u != null && u != "" && this._url != u ){
				this._url = u;
				this._urlChanged = true;
				this.invalidateProperties();
			}
		}
		
		override protected function commitProperties():void {
			if( this.pane && this.pane.map ){
				if( this._urlChanged ){
					this._urlChanged = false
					
					this.removeAll();
						
					this._puller.load( new URLRequest( this._url ) );
				}
			}
			else{
				this.invalidateProperties();
			}
			
			super.commitProperties();
		}
		
		protected function onAmfPullComplete( event:Event ) : void {
			var packages:AmfPackages = AmfFactory.UnPackage( this._puller.data as ByteArray );
			
			if( packages && packages.length == 1 ){
				var p:AmfPackage = packages.getPackage( 0 );
				
				if( p.isValid ){
					var amfs:Array = p.data as Array;
					var numAmfs:int = amfs.length;
					
					var amf:AmfObject = amfs[0] as AmfObject;
					var shapeClass:Class;
					if( amf.geometryType == AmfObject.typePoint ){
						shapeClass = wmgOverlayLayerMarker;
					}
					else if( amf.geometryType == AmfObject.typePolyline ){
						shapeClass = wmgOverlayLayerPolyline;
					}
					else if( amf.geometryType == AmfObject.typePolygon ){
						shapeClass = wmgOverlayLayerPolygon;
					}
					
					
					for( var i:int = 0; i < numAmfs; i++ ){ 
						this.add( new shapeClass(amfs[i]) as wmgOverlayLayerBaseShape );
					}
					
				}
			}
			
			this.dispatchEvent( new Event( "DATA_PULL_COMPLETE" ) );
		}
		
	}
}